﻿<%@ WebHandler Language="C#" Class="ImageRequestHandler" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

public class ImageRequestHandler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");
        string path = context.Server.MapPath(context.Request.QueryString[0]);
        string suffix = path.Split('.')[path.Split('.').Length - 1];
        context.Response.ContentType = string.Format("image/{0}", suffix.ToLower().Equals("png") ? "x-png" : suffix);//设置MIME，如果是png文件，MIME信息为text/x-png
        context.Response.Expires = 60 * 24 * 10;//设置图片10天过期
        ImageFormat ift = ImageFormat.Jpeg;//设置默认文件格式
        Image img = Image.FromFile(path);
        if (suffix.ToLower().Equals("png"))
        {
            ift = ImageFormat.Png;
        }
        else if (suffix.ToLower().Equals("bmp"))
        {
            ift = ImageFormat.Bmp;
        }
        MemoryStream ms = new MemoryStream();
        img.Save(ms, ift);
        context.Response.OutputStream.Write(ms.GetBuffer(), 0, (int)ms.Length);
        ms.Close();
        ms.Dispose();
        img.Dispose();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}